package Classic150;

import java.util.ArrayList;
import java.util.List;

public class 组合 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> comb = new ArrayList<>();
    int n;
    int k;

    /*
        for循环终止条件优化，剪枝
     */
    public List<List<Integer>> combine(int n, int k) {
        this.n = n;
        this.k = k;
        backTracking(1);
        return res;
    }

    private void backTracking(int num) {
        if (comb.size() == k) {
            res.add(new ArrayList<>(comb));
            return;
        }
        for (int i = num; i <= n - (k - comb.size()) + 1; i++) {
            comb.add(i);
            backTracking(i + 1);
            comb.removeLast();
        }
    }
}
